import {config} from '../config.js'

class HTTP{
  request({url,data={},method = 'POST'}){
    return new Promise((resolve, reject)=>{
      this._request(url,resolve,reject,data,method)
    })
  }
  _request(url,resolve,reject,data,method){
    wx.request({
      url: config.api_url + url,
      method: method || "POST",
      header: {
        'Content-Type': 'application/x-www-form-urlencoded',
        'atk': config.token,
        'device':config.device,
        'version':config.version
      },
      data: data,
      success: (result) => {
        data.url = url
        this._log(data,result.data)
        if(result.statusCode === 200){
          resolve(result.data)
          
          // if (result.data.code === 0) {
          // }else{
          //   this._show_error(result.data.code)
          //   debugger;
          // }

          if (result.data.code === 701) {
            wx.login({
              complete: (resw) => {
                if (resw.code) {
                  this._loginCode(resw.code,0).then(
                    resp=>{ 
                      if (resp.code===0) {
                        config.token = resp.data.token || ""
                        config.isMobile = resp.data.isMobile || "0"
                      }
                    }
                  )
                }
              },
            })
          }
        }else{
          reject()
          this._show_error(result.error_code)
        }
      },
      fail: (res) => {
        reject()
        this._show_error(1)
      },
    })
  }
  
  _loginCode(code,userId){
    return this.request({
      url:'user/applet/login',
      data:{
        code:code,
        userId:userId
      }
    })
  }

  _show_error(error_code){
    wx.showToast({
      title: tips[error_code||1] || "应用错误",
      icon: 'none',
    })
  }

  _log(req,res){
    console.log("------------config---------------")
    console.log(config)
    console.log("------------req---------------")
    console.log(req)
    console.log("------------res---------------")
    console.log(res)
  }

  _isUrl(url){
    var isUrl = true
    if (config.mobile && config.mobile.length === 11) {
      return isUrl
    }
    config.urlList.forEach(element => {
      if (element===url) {
        isUrl = false
      }
    });
    return isUrl
  }
  
}

const tips = {
  1:"抱歉，出了一个错误",
  404:"抱歉，路径错误",
  601:"应用错误",
  701:"请登录",
  702:"需要登录",
  1005:"token失效",
  3000:"数据不存在"
}

export {HTTP}
